package xyz.thoughtset.viewer.executor.blocks.executor;

import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import xyz.thoughtset.viewer.common.exc.exceptions.ExecException;
import xyz.thoughtset.viewer.modules.step.entity.BlockTypeEnum;
import xyz.thoughtset.viewer.modules.step.entity.ValueBody;
import xyz.thoughtset.viewer.modules.step.entity.block.BlockBodyEle;
import xyz.thoughtset.viewer.modules.step.entity.block.BlockInfo;
import xyz.thoughtset.viewer.modules.step.entity.block.EleParam;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
public class ValueBlockExecutor extends AbstractBlockExecutor<ValueBody> {


    @Override
    BlockTypeEnum getSupportType() {
        return BlockTypeEnum.VALUE;
    }

    @Override
    public Object executeQuery(BlockInfo block, ExpressionParser parser, Map<String, Object> params, StandardEvaluationContext context) throws ExecException {
        HashMap<String, Object> resultMaps = new HashMap<>();
        BlockBodyEle bodyEle = block.firstBody();
        List<EleParam> eleParams = bodyEle.getParams();
        if (Objects.nonNull(eleParams)){
            int size = eleParams.size();
            for (EleParam blockParam : eleParams){
                Object value = null;
                if(StringUtils.hasLength(blockParam.getDataExp())){
                    String exp =blockParam.getDataExp();
                    exp = blockParam.getDataExp().startsWith("#")?exp:"#"+exp;
                    value = parser.parseExpression(exp).getValue(context);
                }
                //qbid作为值对应名称进行存入
                String key = blockParam.getParamId();
                if (StringUtils.hasText(key)){
                    context.setVariable(key, value);
                    params.put(key, value);
                    resultMaps.put(key, value);
                } else if (size == 1) {
                    return value;
                }
            }
        }
        return resultMaps;
    }

    @Override
    protected Object doQuery(BlockInfo block, ValueBody body, Map<String, Object> params, ExpressionParser parser, StandardEvaluationContext context) throws ExecException {
        return null;
    }
}
